<template>
  <page-card title="业务线条"
             :sub-title="'编辑'"
             :need-back="true">
    <slot name="form" />
    <a-row v-if="!$slots.form"
           :gutter="16">
      <a-col :span="24">
        <a-card :bodyStyle="{overflow: 'auto'}">
          <a-form :form="form"
                  :label-col="{ span: 6 }"
                  :wrapper-col="{ span: 14 }">

            <a-form-item label="线条名称">
              <a-input :maxLength="20"
                       placeholder="请输入线条名称"
                       v-decorator="['businessLineName', { rules: [{ required: true, message: '请填写线条名称!' }] }]" />
            </a-form-item>

          </a-form>
        </a-card>
      </a-col>

    </a-row>
    <div>
      <a-transfer class="tree-transfer"
                  :data-source="dataSource"
                  :target-keys="targetKeys"
                  :selected-keys="checkedKeys"
                  :render="item => item.title"
                  :show-select-all="true"
                  :titles="['组织机构',' 条线范围']"
                  show-search
                  @change="onChange"
                  @search="handleSearch">
        <template slot="children"
                  slot-scope="{ props: { direction, selectedKeys,disabled: listDisabled }, on: { itemSelectAll, itemSelect } }">
          <a-tree v-if="direction === 'left'"
                  blockNode
                  checkable
                  checkStrictly
                  defaultExpandAll
                  :checkedKeys="[...selectedKeys, ...targetKeys]"
                  :treeData="treeData"
                  @check="
                    (_, props) => {
                      onChecked(_, props, [...selectedKeys, ...targetKeys], itemSelect);
                    }
                  "
                  @select="
                    (_, props) => {
                      onChecked(_, props, [...selectedKeys, ...targetKeys], itemSelect);
                    }
                  " />
          <template v-else>
            <a-table :data-source="tableSource"
                     :columns="tableColumns"
                     :rowKey="(record,index)=>record.key"
                     :pagination="false"
                     :row-selection="
                       getRowSelection({ disabled: listDisabled, selectedKeys, itemSelectAll, itemSelect })
                     "></a-table>
          </template>

        </template>
      </a-transfer>
    </div>
    <div style="text-align:center; padding:30px">
      <a-space size="small">
        <slot name="buttons" />
        <template v-if="!$slots.buttons">
          <a-button v-if="$route.query.id && hasPermission('delete')"
                    action
                    @click="handleDelete"
                    style="width:80px;">删除</a-button>
          <a-button type="primary"
                    action
                    @click="handleSave"
                    style="width:80px;">保存</a-button>
        </template>
      </a-space>
    </div>
  </page-card>
</template>

<script>
import Vue from 'vue'
import { Card, message } from 'ant-design-vue'
import ArrayUtil from '@zh/common-utils/utils/array'
import clone from 'clone'
import difference from 'lodash/difference'
import { del, unituser, update, getById } from '../../api/businessline/index'

Vue.use(Card)

const treeData = [
  { key: '0-0', title: '0-0' },
  {
    key: '0-1',
    title: '0-1',
    children: [
      { key: '0-1-0', title: '0-1-0' },
      { key: '0-1-1', title: '0-1-1' }
    ]
  },
  { key: '0-2', title: '0-3' }
]

export default {
  props: {
    onSave: {
      type: Function,
      default: null
    },
    onDelete: {
      type: Function,
      default: null
    }
  },
  data () {
    return {
      targetKeys: [],
      checkedKeys: [],
      dataSource: [],
      form: this.$form.createForm(this, { name: 'coordinated' }),
      data: [],
      unituserlist: [],
      id: this.$route.query.id,
      rangelist: [],
      tableSource: [],
      tableColumns: [
        { title: '', dataIndex: 'name' },
        { title: '', dataIndex: 'type' }
      ],
      zcyblist: [], // 暂存右边list的数据
      xztablist: []
    }
  },

  computed: {
    treeData () {
      return this.handleTreeData(this.data, this.targetKeys)
    }/*,
		rowSelection() {
			return {
				onChange: (selectedRowKeys, selectedRows) => {

				this.xztablist = selectedRows
				},
				getCheckboxProps: record => ({
				props: {
					disabled: record.name === 'Disabled User', // Column configuration not to be checked
					name: record.name,
				},
				}),
			}
        } */
  },
  created () {
    /* this.data = [
      { key: '33', title: '33', pid: '0' },
      { key: '44', title: '44', pid: '0' },
      { key: '55', title: '55', pid: '0' }
    ]

    this.flatten(JSON.parse(JSON.stringify(this.data))) */
    this.unituserpage('')
    // this.targetKeys = ['1666379693101678593']
  },
  methods: {
    unituserpage (obj) {
      const param = { nameall: obj }
      unituser(param).then((rep) => {
        this.data = rep.unitusertree
        if (obj == '') {
          this.unituserlist = rep.unituserlist
          this.getInfo()
        }

        this.flatten(JSON.parse(JSON.stringify(this.data)))
      })
    },
    flatten (list = []) {
      list.forEach((item) => {
        this.dataSource.push(item)
        this.flatten(item.children)
      })
    },
    handleTreeData (data, targetKeys = []) {
      data.forEach((item) => {
        item.disabled = targetKeys.includes(item.key)
        if (item.children) {
          this.handleTreeData(item.children, targetKeys)
        }
      })
      return data
    },
    isChecked (selectedKeys, eventKey) {
      return selectedKeys.indexOf(eventKey) !== -1
    },
    handleSave () {
      this.form.validateFields((err, values) => {
        const ranges = []
        const rangedata = []
        const rangelist = this.rangelist
        const unitusers = this.unituserlist
        const list = this.targetKeys
        let businessLineRange = ''
        for (var i = 0; i < unitusers.length; i++) {
          for (var j = 0; j < list.length; j++) {
            if (unitusers[i].key == list[j]) {
              businessLineRange += unitusers[i].title + '、'
              const range = {
                businessLineRangeId: unitusers[i].key,
                businessLineRange: unitusers[i].title,
                businessLineRangeType: unitusers[i].type
              }
              ranges.push(range)
            }
          }
        }
        for (var i = 0; i < ranges.length; i++) {
          let r = ranges[i]
          for (var j = 0; j < rangelist.length; j++) {
            if (r.businessLineRangeId == rangelist[j].businessLineRangeId) {
              r = rangelist[j]
            }
          }
          rangedata.push(r)
        }
        businessLineRange = businessLineRange.substring(
          0,
          businessLineRange.length - 1
        )

        let name = values.businessLineName
        if (name == null || name.trim() == '') {
          return
        }

        if (rangedata.length == 0) {
          message.info('请添加线条范围！')
          return
        }
        const params = {
          id: this.id,
          businessLineName: name,
          businessLineRange: businessLineRange,
          businessLineRanges: rangedata
        }

        update(params).then((response) => {
          this.$router.push({
            path: '/businessline'
          })
        })
      })
    },
    getInfo () {
      const params = {
        id: this.id
      }
      getById(params).then((response) => {
        this.form.setFieldsValue({
          businessLineName: response.businessLineName
        })
        this.rangelist = response.rangelist
        const list = response.rangelist
        const ranges = []
        for (let i = 0; i < list.length; i++) {
          ranges.push(list[i].businessLineRangeId)
        }

        this.targetKeys = ranges
        this.zcyblist = ranges
        this.getinfotab()
      })
    },
    getinfotab () {
      const uulist = this.unituserlist
      let ranges = this.targetKeys
      let tablist = []
      for (let i = 0; i < uulist.length; i++) {
        let flg = false

        for (let j = 0; j < ranges.length; j++) {
          if (uulist[i].key == ranges[j]) {
            flg = true
          }
        }

        if (flg) {
          let types = ''
          if (uulist[i].type == '2') {
            types = '单位'
          } else if (uulist[i].type == '3') {
            types = '部门'
          } else if (uulist[i].type == '10') {
            types = '人员'
          }
          let aa = { name: uulist[i].title, type: types, key: uulist[i].key }
          tablist.push(aa)
        }
      }

      this.tableSource = tablist
    },

    handleDelete () {
      const me = this
      me.confirm({
        content: '确定删除？',
        okText: '是',
        cancelText: '否',
        onOk () {
          if (me.onDelete != null) {
            me.onDelete(me.form.getFieldValue('id'), me.form).then((res) => {
              me.$router.go(-1)
            })
          } else {
            del(me.form.getFieldValue('id')).then((res) => {
              me.$router.go(-1)
            })
          }
        }
      })
    },

    // 根据勾选的节点将节点中下的所有子节点设置为禁用并清空勾选的子节点值
    setChildNodeDisabled (data, keys = [], isCheckAction = false) {
      data.forEach((item) => {
        if (item.children) {
          const isDisabled = keys.includes(item.key) || item.disabled
          item.children = item.children.map((node) => {
            /**
             * 1. 判断父节点item是否包含在选的keys中，如果存在，则需要将所有的子节点设置为禁用状态
             * 2. 如果是节点移动操作时，需要判断node子节点是否包含在勾选的keys数组，如果存在，则需要将该子节点设置成禁用状态
             */
            node.disabled = isDisabled || (!isCheckAction && keys.includes(node.key))
            return node
          })
          // 是否需要删除子节点操作
          if (isCheckAction && isDisabled) {
            for (const node of item.children) {
              const index = keys.findIndex(key => {
                return key === node.key
              })
              if (index > -1) {
                keys.splice(index, 1)
              }
            }
          }
          this.setChildNodeDisabled(item.children, keys, isCheckAction)
        }
      })
      return data
    },
    onChange (targetKeys, direction, moveKeys) {
      const _this = this
      const tabs = _this.xztablist
      this.checkedKeys = []

      if (tabs.length > 0 && direction == 'left') {
        const keys = _this.targetKeys
        let datas = []
        for (var i = 0; i < keys.length; i++) {
          var flg = true
          for (var j = 0; j < tabs.length; j++) {
            if (keys[i] == tabs[j].key) {
              flg = false
            }
          }
          if (flg) {
            datas.push(keys[i])
          }
        }
        targetKeys = datas
      }
      _this.targetKeys = targetKeys
      _this.zcyblist = targetKeys
      const uulist = _this.unituserlist
      let tablist = []
      for (var i = 0; i < uulist.length; i++) {
        var flg = false
        for (var j = 0; j < targetKeys.length; j++) {
          if (uulist[i].key == targetKeys[j]) {
            flg = true
          }
        }
        if (flg) {
          let types = ''
          if (uulist[i].type == '2') {
            types = '单位'
          } else if (uulist[i].type == '3') {
            types = '部门'
          } else if (uulist[i].type == '10') {
            types = '人员'
          }
          let aa = { name: uulist[i].title, type: types, key: uulist[i].key }
          tablist.push(aa)
        }
      }
      _this.tableSource = tablist
      _this.xztablist = []
      this.handleTreeData(this.data, targetKeys)
      this.setChildNodeDisabled(this.data, targetKeys)
    },
    onChecked (_, e, checkedKeys, itemSelect) {
      const { eventKey } = e.node
      const index = this.checkedKeys.indexOf(eventKey)
      if (index > -1) {
        this.checkedKeys.splice(index, 1)
      } else {
        this.checkedKeys.push(eventKey)
      }
      this.setChildNodeDisabled(this.data, this.checkedKeys, true)
    },
    handleSearch (dir, value) {
      if (dir == 'left') {
        this.dataSource = []
        this.unituserpage(value)
      }
      if (dir == 'right') {
        const xzlist = this.zcyblist
        let zslist = []
        const unituserlists = this.unituserlist
        if (value != null && value.trim() != '') {
          for (var i = 0; i < unituserlists.length; i++) {
            var flg = false
            for (var j = 0; j < xzlist.length; j++) {
              if (unituserlists[i].key == xzlist[j]) {
                flg = true
              }
            }
            if (flg) {
              zslist.push(unituserlists[i])
            }
          }
          let showdata = []
          for (var i = 0; i < zslist.length; i++) {
            if (zslist[i].title.indexOf(value) != -1) {
              showdata.push(zslist[i].key)
            }
          }

          this.targetKeys = showdata
          const uulist = this.unituserlist
          var tablist = []
          for (var i = 0; i < uulist.length; i++) {
            var flg = false
            for (var j = 0; j < showdata.length; j++) {
              if (uulist[i].key == showdata[j]) {
                flg = true
              }
            }
            if (flg) {
              var types = ''
              if (uulist[i].type == '2') {
                types = '单位'
              } else if (uulist[i].type == '3') {
                types = '部门'
              } else if (uulist[i].type == '10') {
                types = '人员'
              }
              var aa = { name: uulist[i].title, type: types }
              tablist.push(aa)
            }
          }
          this.tableSource = tablist
        } else {
          const showdata = this.zcyblist

          this.targetKeys = showdata
          const uulist = this.unituserlist
          var tablist = []
          for (var i = 0; i < uulist.length; i++) {
            var flg = false
            for (var j = 0; j < showdata.length; j++) {
              if (uulist[i].key == showdata[j]) {
                flg = true
              }
            }
            if (flg) {
              var types = ''
              if (uulist[i].type == '2') {
                types = '单位'
              } else if (uulist[i].type == '3') {
                types = '部门'
              } else if (uulist[i].type == '10') {
                types = '人员'
              }
              var aa = { name: uulist[i].title, type: types }
              tablist.push(aa)
            }
          }
          this.tableSource = tablist
        }
      }
    },
    getRowSelection ({ disabled, selectedKeys, itemSelectAll, itemSelect }) {
      const _this = this
      return {
        selectedRowKeys: this.checkedKeys,
        getCheckboxProps: item => ({ props: { disabled: disabled || item.disabled } }),
        onSelectAll (selected, selectedRows) {
          const treeSelectedKeys = selectedRows
            .filter(item => !item.disabled)
            .map(({ key }) => key)
          const diffKeys = selected
            ? difference(treeSelectedKeys, selectedKeys)
            : difference(selectedKeys, treeSelectedKeys)

          itemSelectAll(diffKeys, selected)
        },
        onSelect (row, selected) {
          if (selected) {
            // var tabs = []
            // tabs.push(aa)
            // _this.xztablist = tabs
            _this.xztablist.push(row)
            _this.checkedKeys.push(row.key)
          } else {
            const dels = _this.xztablist
            let tabs = []
            for (let i = 0; i < dels.length; i++) {
              let flg = true
              if (dels[i].key == row.key) {
                flg = false
              }
              if (flg) {
                tabs.push(dels[i])
              }
            }
            _this.xztablist = tabs
            const index = _this.checkedKeys.indexOf(row.key)
            if (index > -1) {
              _this.checkedKeys.splice(index, 1)
            }
          }

          itemSelect(row.key, selected)
        }
      }
    }
  }
}
</script>

<style lang="less" scoped>
::v-deep .ant-checkbox-group-item {
  width: 100%;
  padding: 5px 0;
}
.tree-transfer .ant-transfer-list:first-child {
  width: 50%;
  flex: none;
}
/deep/.ant-table-thead {
  display: none;
}
</style>
